//
//  LoginViewController.m
//  CKApp
//
//  Created by CC on 2020/8/26.
//  Copyright © 2020 This Moment. All rights reserved.
//

#import "LoginViewController.h"
#import "LcFoundation.h"
#import "LoginRequestData.h"
#import "LoginResponseData.h"
#import "PhoneVerifyRequestData.h"
#import "PhoneVerifyResponseData.h"
#import "UserManager.h"
#import "ApiRequestUtil.h"

@interface LoginViewController ()
@property(strong, nonatomic) IBOutletCollection(UIView) NSArray<UIView*>* containerViews;
@property(nonatomic, weak) IBOutlet UITextField* phoneNumberTextField;
@property(nonatomic, weak) IBOutlet UITextField* codeTextField;
@property(nonatomic, weak) IBOutlet UIButton* verifyCodeButton;
@property(nonatomic, weak) IBOutlet UIButton* loginButton;
@property(nonatomic, strong) LcTimerRepeat* timerRepeat;
@property(nonatomic, assign) NSInteger timerCounter;
@property(nonatomic, copy) NSString* msgId;
@end

@implementation LoginViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  [self showCloseButton];
  for (UIView* view in self.containerViews) {
    view.backgroundColor = LC_COLOR_INPUT_BACKGROUND;
    view.layer.cornerRadius = 22.0;
  }

  [self.phoneNumberTextField setLcFont:[LcFont gr14]];
  [self.codeTextField setLcFont:[LcFont gr14]];

  [self refreshVerifyButton];

  [self.loginButton setRedStyle];
  [self.loginButton setTitle:@"登录"];

  [self.phoneNumberTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  [self.codeTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}

- (void)viewDidAppear:(BOOL)animated {
  [super viewDidAppear:animated];
  [self.phoneNumberTextField becomeFirstResponder];
}

- (void)refreshVerifyButton {
  if (self.timerCounter > 0) {
    [self.verifyCodeButton setEnabled:NO];
    [self.verifyCodeButton setLcFont:[LcFont gb14]];
    [self.verifyCodeButton setTitle:[NSString stringWithFormat:@"%zds", self.timerCounter]];
  } else {
    [self.verifyCodeButton setEnabled:YES];
    [self.verifyCodeButton setLcFont:[LcFont rb14]];
    [self.verifyCodeButton setTitle:@"发送验证码"];
  }
}

- (void)startTimer {
  [self.timerRepeat stop];
  self.timerCounter = 30;
  self.timerRepeat =
      [LcTimerRepeat timerWithInterval:1
                                 block:^(LcTimerRepeat* timer) {
                                   self.timerCounter--;
                                   [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                                     [self refreshVerifyButton];
                                   }];
                                   if (self.timerCounter <= 0) {
                                     [self.timerRepeat stop];
                                   }
                                 }];
  [self.timerRepeat start];
}

#pragma mark - ButtonAction
- (IBAction)veriyCodeClicked:(id)sender {
  NSString* phoneNumer = [self.phoneNumberTextField text];
  if ([phoneNumer isValidPhoneNumber]) {
    [self requestVerifyData:phoneNumer];
  } else {
    [LcToast showToastWithMessage:@"手机号码格式不正确，请重新输入"];
  }
}

- (IBAction)loginClicked:(id)sender {
  NSString* phoneNumer = [self.phoneNumberTextField text];
  NSString* verifyCode = [self.codeTextField text];
  if (![phoneNumer isValidPhoneNumber]) {
    [LcToast showToastWithMessage:@"手机号码格式不正确，请重新输入"];
    return;
  } else if (verifyCode == nil || verifyCode.length == 0) {
    [LcToast showToastWithMessage:@"请输入验证码"];
    return;
  }
  [self requestLoginData];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField*)textField {
  if (textField == self.codeTextField) {
    [textField resignFirstResponder];
    [self requestLoginData];
  }
  return YES;
}

- (void)textFieldDidChange:(UITextField*)textField {
  if (self.phoneNumberTextField.text.length > 0 && self.codeTextField.text.length > 0) {
    [self.loginButton setEnabled:YES];
  } else {
    [self.loginButton setEnabled:NO];
  }
}

#pragma mark - RequestData
- (void)requestVerifyData:(NSString*)phone {
  PhoneVerifyRequestData* requestData = [[PhoneVerifyRequestData alloc] init];
  requestData.account = phone;
  LcWeakSelf;
  [ApiRequestUtil sendRequest:requestData successHandler:^(__kindof CCRequestData *requestData, PhoneVerifyResponseData* responseData) {
    LcStrongSelf;
    [self startTimer];
    self.msgId = responseData.data.msg_id;
  } errorHandler:^(__kindof CCRequestData *requestData, LcApiError *apiError) {

  } showModalLoadingIndicator:NO];
}

- (void)requestLoginData {
  LoginRequestData* requestData = [[LoginRequestData alloc] init];
  requestData.account = self.phoneNumberTextField.text;
  requestData.verify_code = self.codeTextField.text;
  requestData.msg_id = self.msgId;
  LcWeakSelf;
  [ApiRequestUtil sendRequest:requestData successHandler:^(__kindof CCRequestData *requestData, LoginResponseData* responseData) {
    LcStrongSelf;
    [[UserManager sharedInstance] didLogin:responseData.data.info
                               clientToken:responseData.data.user_session_id];
    [self dismissViewControllerAnimated:YES completion:^{
      if (self.completeBlock != nil) {
        self.completeBlock(YES);
      }
    }];
  } errorHandler:^(__kindof CCRequestData *requestData, LcApiError *apiError) {

  } showModalLoadingIndicator:YES];
}

@end
